﻿#include "progresswait.h"

ProgressWait::ProgressWait(QWidget *parent) : QWidget(parent)
{
    initState();
}

void ProgressWait::initState()
{
    currentValue = 0;
//    this->setStyleSheet("background-color:transparent");
//    setWindowOpacity(0.4);
//    this->setAttribute(Qt::WA_TranslucentBackground, true);

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&ProgressWait::updateCurrentValue);
}

void ProgressWait::startWait()
{
    this->show();
    timer->start(150);
}

void ProgressWait::stopWait()
{
    if(timer->isActive())
    {
        timer->stop();
    }

    if(this->isVisible())
    {
        this->hide();
    }
}

void ProgressWait::drawLine(QPainter *painter)
{
    int radius = 100;

    //这个Y轴坐标控制线条的高度,默认为半径的一半,值越大线条越短
    int initY = 40;

    painter->save();
    painter->setBrush(Qt::NoBrush);
    int width = this->width();
    int height = this->height();
    int side = qMin(width, height);

    //绘制准备工作,启用反锯齿,平移坐标轴中心,等比例缩放
    painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter->translate(width / 2, height / 2);
    painter->scale(side / 500.0, side / 500.0);

    QPen pen;
    pen.setWidth(10);
    pen.setCapStyle(Qt::RoundCap);

    double angleStep = 360.0 / 10;
    double alpha = (double)1 / 10;

    for (int i = 0; i <= 10; i++)
    {
        int value = (currentValue - i) * alpha * 255;
        if (value < 0)
        {
            value = value + 255;
        }

        value = value < 30 ? 30 : value;

        QColor color = QColor(100, 184, 255);
        color.setAlpha(value);
        pen.setColor(color);
        painter->setPen(pen);
        painter->drawLine(0, initY, 0, radius);
        painter->rotate(angleStep);
    }

    painter->restore();
}

void ProgressWait::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    drawLine(&painter);
}

void ProgressWait::updateCurrentValue()
{
    if (currentValue < 10)
    {
        currentValue++;
    }
    else
    {
        currentValue = 0;
    }

    update();
}
